import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    TouchableOpacity,
    ScrollView,
    ImageBackground
} from 'react-native';
import {Button, ActionSheet} from 'react-native-ui-lib'
import {connect} from 'react-redux';
import FastImage from 'react-native-fast-image'
import {ListRow, Toast} from 'teaset'
import ImagePicker from 'react-native-image-crop-picker';

import Global from '../common/global'
import colors from '../common/colors'
import Util from '../common/util'
import LoadingModal from '../common/LoadingModal'
import * as TYPES from '../common/type'
import store from '../store/store'
import {getUserInfo} from '../actions/mineAction'

class Mine extends Component {
    static navigationOptions = ({navigation, screenProps}) => ({
        title: '我的',
        color: colors.primaryColor,
        tabBarIcon: ({focused, tintColor}) => {
            if (focused) {
                return <Image source={require('../images/tabbar_icon_med.png')}
                              style={{width: 25, height: 25}}
                />
            } else {
                return <Image source={require('../images/tabbar_icon_me.png')}
                              style={{width: 25, height: 25}}
                />
            }
        },
        headerBackTitle: null,
        tabBarOnPress: ({navigation, defaultHandler}) => {
            store.dispatch(getUserInfo())
            defaultHandler()
        }
    })


    constructor(props) {
        super(props);
        this.state = {
            loadError: false,
            showActionSheet: false,
            isLoading: false
        };
    }

    changeLoadingStatus = (flag) => {
        this.setState({
            isLoading: flag
        })
    }

    pressSettings = () => {
        this.props.navigation.navigate('Settings')
    }

    pressTask = (index) => {
        this.props.navigation.navigate('TaskList', {
            from: index == 1 ? 'send' : 'receive',
            title: index == 1 ? '指派的任务' : '收到的指派'
        })
    }

    pressHeader = () => {
        this.setState({
            showActionSheet : true
        })
    }

    renderHeader = () => {
        let User = this.props.User
        let source = User.pic ? {uri: User.pic} : require('../images/header.png')
        return (
            <View style={styles.headerContainer}>
                <ImageBackground style={styles.bgImage} source={require('../images/me_bg.png')}>
                    <View style={{
                        height: 50,
                        width: Global.width,
                        paddingRight: 12,
                        alignItems: 'flex-end',
                        justifyContent: 'center'
                    }}>
                        <Button
                            iconSource={require('../images/nav_ico_setting.png')}
                            iconStyle={{width: 24, height: 24, tintColor: '#fff'}}
                            link
                            onPress={this.pressSettings}
                        />
                    </View>
                    <View style={{flex: 1, alignItems: 'center', justifyContent: 'center', paddingBottom: 15}}>
                        <TouchableOpacity activeOpacity={0.8} onPress={this.pressHeader}>
                            <View style={{alignItems: 'center', justifyContent: 'center'}}>
                                <FastImage style={styles.header} source={source}/>
                                <Text style={{
                                    marginTop: 20,
                                    fontWeight: 'bold',
                                    fontSize: 17,
                                    color: '#fff'
                                }}>{User.un}</Text>
                                <Text style={{
                                    marginTop: 10,
                                    fontSize: 13,
                                    color: '#fff'
                                }}>
                                    {User.dept}
                                </Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                </ImageBackground>
                {
                    User.role == 1 ? (
                        <View style={{
                            flexDirection: 'row',
                            alignItems: 'center',
                            width: Global.width,
                            height: 97,
                            backgroundColor: '#fff'
                        }}>
                            <TouchableOpacity style={styles.perView} activeOpacity={0.8} onPress={() => this.pressTask(1)}>
                                <Text style={styles.title}>{User.left_num}</Text>
                                <Text style={styles.subTitle}>指派任务</Text>
                            </TouchableOpacity>
                            <View style={{width: 1, height: 40, backgroundColor: '#DCDCDC'}}/>
                            <TouchableOpacity style={styles.perView} activeOpacity={0.8} onPress={() => this.pressTask(2)}>
                                <Text style={styles.title}>{User.right_num}</Text>
                                <Text style={styles.subTitle}>收到的指派</Text>
                            </TouchableOpacity>
                        </View>
                    ) : (
                        <View style={{
                            flexDirection: 'row',
                            alignItems: 'center',
                            width: Global.width,
                            height: 97,
                            backgroundColor: '#fff'
                        }}>
                            <TouchableOpacity style={styles.perView} activeOpacity={0.8} onPress={() => this.pressTask(2)}>
                                <Text style={styles.title}>{User.right_num}</Text>
                                <Text style={styles.subTitle}>收到的指派</Text>
                            </TouchableOpacity>
                        </View>
                    )
                }
            </View>
        )
    }

    pressNotice = () => {
        this.props.navigation.navigate('SystemNotice')
    }

    renderContent = () => {
        return (
            <View style={{marginTop: 10}}>
                <ListRow
                    title={"系统通知"}
                    titleStyle={styles.listRowTitle}
                    bottomSeparator={"none"}
                    onPress={this.pressNotice}
                />
            </View>
        )
    }

    changePic = (file) => {
        this.changeLoadingStatus(true);
        Util.uploadmultiImages(Api.ChangePhoto, {
            uid: Global.uid,
            pic: file
        })
            .then(({code, msg, data}) => {
                this.changeLoadingStatus(false);
                if (code == '0') {
                    this.props.dispatch({
                        type: TYPES.UPDATE_USER_INFO,
                        info: {
                            pic: data.pic
                        },
                    })
                } else {
                    Toast.fail(msg)
                }
            }).catch(error => {
            this.changeLoadingStatus(false);
            console.log(error)
            Toast.fail(Util.ErrorMessage)
        });
    }

    selectCamera = () => {
        let imagePickerParam = {
            width: 400,
            height: 400,
            cropping: true,
            mediaType: 'photo',
            compressImageQuality: 0.5,
            cropperChooseText: '选择',
            cropperCancelText: '取消'
        }

        ImagePicker.openCamera(imagePickerParam).then(image => {
            let file = {
                uri: image.path,
                type: 'multipart/form-data',
                name: image.filename ? image.filename : image.modificationDate
            };

            this.changePic(file)
        }).catch(e => {
            console.log(e)
        });
    }

    selectImg = () => {
        let imagePickerParam = {
            width: 400,
            height: 400,
            cropping: true,
            mediaType: 'photo',
            compressImageQuality: 0.5,
            cropperChooseText: '选择',
            cropperCancelText: '取消'
        }

        ImagePicker.openPicker(imagePickerParam).then(image => {
            let file = {
                uri: image.path,
                type: 'multipart/form-data',
                name: image.filename ? image.filename : image.modificationDate
            };
            this.changePic(file)
        }).catch(e => {
            console.log(e)
        });
    }

    renderActionSheet = () => {
        return (
            <ActionSheet
                title="更换头像"
                message="请选择使用相机或者相册"
                useNativeIOS
                cancelButtonIndex={2}
                options={[
                    {label: '相机', onPress: () => this.selectCamera()},
                    {label: '相册', onPress: () => this.selectImg()},
                    {
                        label: '取消', onPress: () => {
                        }
                    },
                ]}
                visible={this.state.showActionSheet}
                onDismiss={() => this.setState({showActionSheet: false})}
            />
        )
    }

    render() {
        return (
            <View style={styles.container}>
                <ScrollView style={{flex: 1}}>
                    {this.renderHeader()}
                    {this.renderContent()}
                </ScrollView>
                {this.renderActionSheet()}
                <LoadingModal isOpen={this.state.isLoading}/>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: colors.bgColor
    },
    bgImage: {
        width: Global.width,
        height: Global.width * 240 / 375,
        paddingTop: Global.paddingTop
    },
    headerContainer: {
        backgroundColor: '#fff'
    },
    header: {
        height: 80,
        width: 80,
        borderRadius: 40,
        borderWidth: 3,
        borderColor: '#fff'
    },
    perView: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    },
    title: {
        fontSize: 30,
        color: '#222222',
        marginBottom: 20
    },
    subTitle: {
        fontSize: 15,
        color: '#222222'
    },
    listRowTitle: {
        fontSize: 15,
        color: '#222222'
    }
});

function select(state) {
    return {
        User: state.User,
    }
}

export default connect(select)(Mine);